package com.cays.myresearch.activity;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.cays.myresearch.R;
import com.cays.myresearch.Util.HttpUtil;
import com.cays.myresearch.action.LoginAction;
import com.cays.myresearch.constant.Constant;
import com.cays.myresearch.entity.Classes;
import com.cays.myresearch.entity.ResponseInfo;
import com.cays.myresearch.entity.Teacher;
import com.cays.myresearch.entity.UserInfo;
import com.cays.myresearch.ui.HeadControlPanel;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Response;

public class PostClassActivity extends AppCompatActivity implements
    HeadControlPanel.HeadPanelCallback,View.OnClickListener{
    private HeadControlPanel postClassHeader;
    private Button postClassSubmitBtn;
    private Button postClassCancelBtn;
    private Classes changeClass;
    private EditText postClassTitle;
    private EditText postClassInstruction;
    private EditText postClassTeacher;
    private EditText postClassType;
    private EditText postClassPrice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String s=getIntent().getStringExtra("change_class");
        if (s!=null&&!s.isEmpty())
            changeClass=Constant.gson.fromJson(s,
                new TypeToken<Classes>(){}.getType());
        setContentView(R.layout.activity_post_class);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        initView();
    }
    private void initView(){
        if(postClassHeader==null){
            postClassHeader=(HeadControlPanel)findViewById(R.id.post_class_header);
            postClassHeader.initHeadPanel();
            postClassHeader.setHeadPanelCallback(this);
        }
        postClassHeader.setLeftImage(R.drawable.ic_back);
        if (changeClass!=null){
            postClassHeader.setMiddleTitle("修改课程");
        }else {
            postClassHeader.setMiddleTitle("发布课程");
        }
        postClassHeader.setRightTitle("");

        postClassSubmitBtn = (Button) findViewById(R.id.post_class_submit_btn);
        postClassSubmitBtn.setOnClickListener(this);
        postClassCancelBtn = (Button) findViewById(R.id.post_class_cancel_btn);
        postClassCancelBtn.setOnClickListener(this);

        postClassTitle = (EditText) findViewById(R.id.post_class_title);
        postClassInstruction = (EditText) findViewById(R.id.post_class_instruction);
        postClassTeacher = (EditText) findViewById(R.id.post_class_teacher);
        postClassType = (EditText) findViewById(R.id.post_class_type);
        postClassPrice = (EditText) findViewById(R.id.post_class_price);
        if (changeClass!=null){
            postClassTitle.setText(changeClass.getTitle());
            postClassInstruction.setText(changeClass.getInstruction());
            postClassTeacher.setText(changeClass.getTeacher());
            postClassType.setText(changeClass.getType());
            postClassPrice.setText(""+changeClass.getPrice());
        }
    }
    @Override
    public void onHeadPanelClick(int itemId) {
        switch (itemId){
            case Constant.btn_left_title:
                finish();
                break;
            case Constant.btn_middle_title:
                break;
            case Constant.btn_right_title:
                break;
            default:break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.post_class_submit_btn:
                if (changeClass==null){
                    sendClasses();
                }else{
                    changeMyClass(changeClass);
                }
                break;
            case R.id.post_class_cancel_btn:finish();break;
            default:break;
        }
    }
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what==1){
                String s=(String)msg.obj;
                ResponseInfo responseInfo=Constant.gson.fromJson(s,
                        new TypeToken<ResponseInfo>(){}.getType());
                Toast.makeText(getApplicationContext(),responseInfo.getResponseInfo(),
                        Toast.LENGTH_SHORT).show();
                if (responseInfo.getResponseCode()==200){
                    finish();
                }
            }else if(msg.what==0){
                Toast.makeText(getApplicationContext(),"未知错误",
                        Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    });
    private void sendClasses(){
        String title=postClassTitle.getText().toString();
        String instruction=postClassInstruction.getText().toString();
        String teacher=postClassTeacher.getText().toString();
        String type=postClassType.getText().toString();
        String price=postClassPrice.getText().toString();
        if (title.isEmpty()||instruction.isEmpty()||teacher.isEmpty()||
                type.isEmpty()||price.isEmpty()){
            Toast.makeText(this,"输入有误",Toast.LENGTH_SHORT).show();
            return;
        }
        LoginAction loginAction=new LoginAction();
        if (!loginAction.hasUserInfo(getApplicationContext())){
            Toast.makeText(this,"未登录",Toast.LENGTH_SHORT).show();
            return;
        }
        UserInfo userInfo=loginAction.getUserInfo(getApplicationContext());
        if (userInfo.getType()!=Constant.user_teacher){
            Toast.makeText(this,"用户不是教师",Toast.LENGTH_SHORT).show();
            return;
        }
        Teacher teacher1=Constant.gson.fromJson(userInfo.getUser(),
                new TypeToken<Teacher>(){}.getType());
        Classes classes=teacher1.issueClass(title,instruction,teacher,type,Double.parseDouble(price));
        final MultipartBody.Builder builder=new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);final String url;
        if (changeClass==null) {
            builder.addFormDataPart("add_class", Constant.gson.toJson(classes));
            url = Constant.URL + "class/add";
        }else{
            builder.addFormDataPart("change_class", Constant.gson.toJson(classes));
            builder.addFormDataPart("change_time",changeClass.getDate());
            url = Constant.URL + "class/change";
        }
        HttpUtil.sendHttpRequest(url,builder,handler,1,0);
    }
    private void changeMyClass(Classes classes){
        if (!checkPremission(classes))return;
    }
    private boolean checkPremission(Classes classes){
        LoginAction loginAction=new LoginAction();
        if(!loginAction.hasUserInfo(getApplicationContext())){
            Toast.makeText(getApplicationContext(),"未登录",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        UserInfo userInfo=loginAction.getUserInfo(getApplicationContext());
        if(userInfo.getType()!=Constant.user_teacher){
            Toast.makeText(getApplicationContext(),"不是教师",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!userInfo.getName().equals(classes.getName())){
            Toast.makeText(getApplicationContext(),"不是本人",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
}
